<?php
include ("connection.php");

function ConnectDB(){
	/*
	$mysqli = new mysqli("localhost", "root", "", "Garmor", 3306);
	if ($mysqli->connect_errno) {
	    echo "Fallo al conectar a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
	}
	*/
	
	$mysqli = new connection();
	if ($mysqli->connect_errno) {
	    echo "Fallo al conectar a MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
	}
	
	return $mysqli;
}

if($_POST)
{	


	$projectName = $_POST['projectName'];
	$projectDescription = $_POST['projectDescription'];
	$projectInsertedIds = explode(",", $_POST['projectInsertedIds']);

	$link = ConnectDB();

	$stmt = $link->prepare("INSERT INTO projects (ProjectName,ProjectDescription) VALUES (?,?);");
	$stmt->bind_param("ss", $projectName, $projectDescription);
	$stmt->execute();
	$projectId = $stmt->insert_id;
	$stmt->close();

	for($i = 0; $i < count($projectInsertedIds); $i++){
		$stmt = $link->prepare("UPDATE images SET ProjectId = ? WHERE ImageId = ?;");
		$stmt->bind_param("ii", $projectId, $projectInsertedIds[$i]);
		$stmt->execute();
		$stmt->close();
	}
}

?>